package handler

import (
	"context"
	"errors"
	"github.com/jinzhu/gorm"
	"gomicrodemo/proto/user"
	"gomicrodemo/changgou-user_service/mq"
	"gomicrodemo/changgou-user_service/service"
	"log"
)

type Handler struct {
	DBAgent service.DBAgent
}

func NewUserHandler(db *gorm.DB) user.UserHandler {
	return Handler{
		DBAgent: service.DBAgent{
			DB: db,
		},
	}
}

func (h Handler) UserExport(ctx context.Context, request *user.UserExportRequest, response *user.UserExportResponse) error {

	resultUsers, err := h.DBAgent.DescribeUsers(request)
	if len(resultUsers) == 0 {
		log.Printf("No user data is available")
		return errors.New("No user data is available")
	}
	if err != nil {
		return err
	}

	response.Users = resultUsers
	return nil
}

func (h Handler) UserLogin(ctx context.Context, request *user.UserLoginRequest, response *user.UserLoginResponse) error {

	message, token := h.DBAgent.UserLogin(request.Username, request.Password)
	//给响应参数赋值
	response.Message = message
	response.Token = token
	//登录成功，发mq庆祝
	mq.Publish(request.Username + "登录成功")
	return nil
}

func (h Handler) UserRegistry(ctx context.Context, request *user.UserRegistryRequest, response *user.UserLoginResponse) error {

	username := request.GetUsername()
	password := request.GetPassword()
	email := request.GetEmail()
	message, token := h.DBAgent.UserRegistry(username, password, email)

	//给响应参数赋值
	response.Message = message
	response.Token = token
	return nil
}

/*
对外界提供一个调用微服务的对象,
为什么返回handler{}就可以：因为 type handler struct{}继承了pb.micro.go里面的(go的继承是实现了对象里面的所有成员)
type UserHandler interface {
	UserRegistry(context.Context, *UserRegistryRequest, *UserLoginResponse) error
	UserLogin(context.Context, *UserLoginRequest, *UserLoginResponse) error
}

*/

